package com.hxd.mall.module

import android.view.View
import android.widget.TextView
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.hexin.locallibrary.permssion.PermissionUtils.showPermissionsTextDialog
import com.hxd.mall.R
import com.hxd.mall.base.BaseInjectActivity
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_web_url
import com.hxd.mall.constant.HxdConstants.isRefuseNotify
import com.hxd.mall.constant.HxdConstants.openedDialog
import com.hxd.mall.constant.HxdConstants.openedHome
import com.hxd.mall.constant.HxdConstantsRouterPath.Common.path_to_webview
import com.hxd.mall.constant.HxdConstantsRouterPath.Product.path_hxd_main_page
import com.hxd.mall.module.product.home.HomeFragment
import com.hxd.mall.module.product.home.HomeViewPagerAdapter
import com.hxd.mall.module.product.home.bean.DataLayout
import com.hxd.mall.module.product.home.bean.Resource
import com.hxd.mall.module.school.enter.SchoolFragment
import com.hxd.mall.module.usercenter.home.MineFragment
import com.hxd.mall.utils.local.*
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.getBooleanData
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.getStringData
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.saveBooleanData
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.saveStringData
import com.hxd.mall.utils.local.NavigationUtil.routerNavigation
import com.hxd.mall.utils.open.DataCleanManager.clearCache
import com.hxd.mall.utils.open.PermissionUtil.toOpenNotify
import com.hxd.mall.utils.open.load
import com.hxd.mall.utils.open.showConfirmWithCancelTitleDialog
import crossoverone.statuslib.StatusUtil.setUseStatusBarColor
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.dialog_pic_layout.*
import kotlinx.android.synthetic.main.layout_main_tab.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.jetbrains.anko.displayMetrics

/**
 * 首页
 */
@Route(path = path_hxd_main_page)
class MainActivity : BaseInjectActivity<IMainPresenter>(), IMainView {

    var current = 0

    override fun attachLayoutRes(): Int = R.layout.activity_main

    override fun initViews() {
        EventBus.getDefault().register(this)

        //设置主页的子页数据
        setViewPage()
        //添加滑动监听
//        addPageChangeListener()
        //主页底部tab的点击监听
        addTabClick()

        setUseStatusBarColor(this, resources.getColor(R.color.color_E24840))
    }

    override fun initData() {
        mPresenter?.getVersionInfo()
    }

    @Subscribe
    fun onEvent(eventBus: EventBean) {
        if (eventBus.index in 0..2) {
            setTabBg(eventBus.index)
        }
    }

    override fun onStart() {
        super.onStart()
        //先清除缓存
        clearCache(this, 100)

        //判断是否要显示协议弹窗
        if (!getBooleanData(openedDialog, false)) {
            //点击同意后才能继续
            showConfirmWithCancelTitleDialog {
                saveBooleanData(openedDialog, true)
            }
            return
        }
        // areNotificationsEnabled方法的有效性官方只最低支持到API 19，低于19的仍可调用此方法不过只会返回true，即默认为用户已经开启了通知。
        val isOpened = NotificationManagerCompat.from(this).areNotificationsEnabled()
        if (!isOpened && !getBooleanData(isRefuseNotify, false)) {
            showPermissionsTextDialog(this, "要允许锦鲤口袋推送通知消息么？包括声音，图标和佣金到账消息内容等。", 10009) {
                if (!it)
                    toOpenNotify(this)
            }

            //表示提示过
            saveBooleanData(isRefuseNotify, true)
        }
    }

    //悬浮布局
    fun showPopoverDialog(popoverLayout: DataLayout?) {
        val popoverList = popoverLayout?.resources ?: mutableListOf()
        if (popoverList.isNotEmpty()) {
            val time = getStringData(openedHome, "0")
            //判断今日是否显示过
            if (time.isNotEmpty() && !TimeUtil.isTaday(time.toLong())) {
                val resource = popoverList[0]
                val show = resource.ext?.isShow ?: false
                if (show) {
                    showDialog(resource)
                }
            }
        }
    }

    private fun showDialog(resource: Resource) {
        saveStringData(openedHome, System.currentTimeMillis().toString())

        layout_home_teach.visibility = View.VISIBLE

        val params = layout_content.layoutParams
        params.width = displayMetrics.widthPixels * 4 / 5
        params.height = displayMetrics.widthPixels * 4 / 5
        layout_content.layoutParams = params

        iv_close.setOnClickListener {
            layout_home_teach.visibility = View.GONE
        }
        layout_root_content.setOnClickListener { }

        iv_piv.load(resource.pictUri, R.mipmap.product_item_icon, R.mipmap.product_item_icon, 20)

        iv_piv.setOnClickListener {
            layout_home_teach.visibility = View.GONE
            routerNavigation(path_to_webview, key_web_url, resource.entryUri ?: "")
        }
    }

    override fun updateData(updateInfoBean: UpdateInfoBean) {
        updateInfoBean.data.run {
            if (status == "update") {
                AppUpdateUtils().showUpdateDialog(this@MainActivity, upgradePoint ?: arrayListOf(), versionType.toString(), versionCode, apkUrl)
            }
        }
    }

    private fun setViewPage() {
        arrayListOf(HomeFragment(), SchoolFragment(), MineFragment()).run {
            //setting vp cache number
            vp_home.offscreenPageLimit = size
            vp_home.currentItem = 0

            vp_home.adapter = HomeViewPagerAdapter(supportFragmentManager).apply {
                setFragmentList(this@run)
            }
        }

        vp_home.postDelayed({
            //初始化后触发一下首页的刷新
            (vp_home.adapter as HomeViewPagerAdapter).getItem(0).setMenuVisibility(true)
        }, 300)
    }

//    private fun addPageChangeListener() {
//        addOnPageChangeListener(vp_home) {
//            // 未登录
//            /*if (it == 1 && HxdConstantsAccount.User_Free_For_Main_Page) {
//                ActivityUtil.jump {}
//                return@addOnPageChangeListener
//            }
//            setTabBg(vp_home.currentItem)*/
//        }
//    }

    override fun onResume() {
        super.onResume()
        sendPoint(vp_home.currentItem)
    }

    private fun addTabClick() {
        tv_home.setOnClickListener {
            setTabOnClick(0)
        }
        tv_guest.setOnClickListener {
            ActivityUtil.jump {
                setTabOnClick(1)
            }
        }
        tv_mine.setOnClickListener {
            ActivityUtil.jump {
                setTabOnClick(2)
            }
        }
    }

    private fun setTabOnClick(index: Int) {
        if (vp_home.currentItem != index) {
            sendPoint(index)
        }
        setTabBg(index)
    }

    private fun sendPoint(index: Int) {
        when (index) {
            0 -> sendPoint(home_page_view)
            1 -> sendPoint(commercial_college_view)
            2 -> sendPoint(personal_center_view)
        }
    }

    //设置tab样式
    private fun setTabBg(index: Int) {
        var index0 = R.mipmap.tab_home_unselect
        var index1 = R.mipmap.tab_school_unselect
        var index2 = R.mipmap.tab_me_unselect
        when (index) {
            0 -> {
                //设置tab字体颜色
                setTextColor(tv_home, true)
                setTextColor(tv_guest, false)
                setTextColor(tv_mine, false)
                index0 = R.mipmap.tab_home_select
            }
            1 -> {
                setTextColor(tv_home, false)
                setTextColor(tv_guest, true)
                setTextColor(tv_mine, false)
                index1 = R.mipmap.tab_school_select
            }
            2 -> {
                setTextColor(tv_home, false)
                setTextColor(tv_guest, false)
                setTextColor(tv_mine, true)
                index2 = R.mipmap.tab_me_select
            }
        }
        //设置tab图标
        setTabDrawableBg(tv_home, index0)
        setTabDrawableBg(tv_guest, index1)
        setTabDrawableBg(tv_mine, index2)

        vp_home.setCurrentItem(index, false)
    }

    private fun setTextColor(textView: TextView, isCheck: Boolean) {
        textView.setTextColor(ContextCompat.getColor(this, if (isCheck) R.color.color_E24840 else R.color.color_666666))
    }

    private fun setTabDrawableBg(tv: TextView, drawableId: Int) =
        tv.setCompoundDrawablesWithIntrinsicBounds(
            null,
            resources.getDrawable(drawableId),
            null,
            null
        )

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

}
